<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同编号" prop="contractCode">
        <el-input v-model="queryParams.contractCode" placeholder="请输入合同编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customName">
        <el-input v-model="queryParams.customName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--<el-form-item label="订单日期">
        <el-date-picker v-model="daterangeOrderDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>-->
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择" clearable>
          <el-option v-for="dict in dict.type.order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleSync"
          v-hasPermi="['order:orderinfo:edit']">同步金蝶销售订单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              border style="width:100%;" :data="orderinfoList"
              @selection-change="handleSelectionChange"
      >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column label="订单合同号" align="center" prop="contractCode" />
      <el-table-column label="单据编号" align="center" prop="orderCode" />
      <el-table-column label="客户名称" align="center" prop="customName" />
      <el-table-column label="订单日期" align="center" prop="orderDate" width="120px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="创建订单时间" align="center" prop="orderCreatetime">
      <template slot-scope="scope">
            <span>{{ parseTime(scope.row.orderCreatetime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>-->
      <el-table-column label="销售部门" align="center" prop="sailDepart" width="80px"/>
      <el-table-column label="跟单员" align="center" prop="documentaryName" width="80px"/>
      <!--<el-table-column label="业务员" align="center" prop="businessName" />-->
      <el-table-column label="订单数量" align="center" prop="orderNum" width="80px"/>
      <el-table-column label="订单状态" align="center" prop="orderStatus" width="80px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>
      <el-table-column label="订单进度" align="center" prop="progress" >
        <template slot-scope="scope">
          <span><a style="color: #0000FF;" @click="showProgress(scope.row)" href="javascript:void(0)">{{scope.row.progress }}</a></span>
        </template>
      </el-table-column>
       <!--<el-table-column label="备注" align="center" prop="orderRemark" />-->
       <el-table-column label="预计完成时间" align="center" prop="planFinishdate">
         <template slot-scope="scope">
            <span>{{ parseTime(scope.row.planFinishdate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
       <el-table-column label="同步日期" align="center" prop="syncTime">
         <template slot-scope="scope">
            <span>{{ parseTime(scope.row.syncTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleView(scope.row)"
            v-hasPermi="['order:orderinfo:edit']">查看详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleOneSync(scope.row)"
            v-hasPermi="['order:orderinfo:edit']">变更同步</el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     v-if="scope.row.orderStatus == 10"
                     @click="headOrderCancel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1700px" :close-on-click-modal ="false" append-to-body>
      <el-form :model="queryParamsOfDialog" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="合同编号" prop="contractCode">
          <el-input v-model="queryParamsOfDialog.contractCode" placeholder="请输入合同编号" clearable @keyup.enter.native="getNeedToCreateList" />
        </el-form-item>
        <el-form-item label="订单编号" prop="contractCode">
          <el-input v-model="queryParamsOfDialog.orderCode" placeholder="请输入订单编号" clearable @keyup.enter.native="getNeedToCreateList" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customName">
          <el-input v-model="queryParamsOfDialog.customName" placeholder="请输入客户名称" clearable @keyup.enter.native="getNeedToCreateList" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getNeedToCreateList">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleCreateOrder"
            v-hasPermi="['order:orderinfo:remove']">批量创建订单</el-button>
        </el-col>
      </el-row>
      <el-table border v-loading="loading" :data="orderCreateinfoList" @selection-change="handleSelectionChange">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="合同编号" align="center" prop="contractCode" width="120"/>
        <el-table-column label="客户名称" align="center" prop="customName" />
        <el-table-column label="订单编号" align="center" prop="orderCode" />
        <el-table-column label="订单状态" align="center" prop="orderStatusDesc" width="125">
          <template slot-scope="scope">
            <el-tag type="success">{{scope.row.orderStatusDesc}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订单日期" align="center" prop="orderDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建订单时间" align="center" prop="orderCreatetime" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.orderCreatetime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单同步时间" align="center" prop="syncTime" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.syncTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="销售部门" align="center" prop="sailDepart" />
        <el-table-column label="跟单员" align="center" prop="documentaryName" />
        <el-table-column label="业务员" align="center" prop="businessName" />
        <el-table-column label="订单数量" align="center" prop="orderNum" />
        <el-table-column label="备注" align="center" prop="orderRemark" />
        <el-table-column label="同步备注" align="center" prop="syncDesc">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.syncDesc==='新订单同步'">{{scope.row.syncDesc}}</el-tag>
            <el-tag v-else-if="scope.row.syncDesc != null">{{scope.row.syncDesc}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleCreateOrder(scope.row)"
              v-hasPermi="['order:orderinfo:edit']">创建订单</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination :total="createtotal" :page.sync="queryParamsOfDialog.pageNum"
        :limit.sync="queryParamsOfDialog.pageSize" @pagination="getCreateList" />
    </el-dialog>

    <el-dialog title="查看订单详情" :visible.sync="viewopen" width="1400px" append-to-body>
      <el-divider></el-divider>
      <el-descriptions title="" direction="vertical" :column="4" border>
        <el-descriptions-item label="合同编号">{{ form.contractCode }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ form.customName }}</el-descriptions-item>
        <el-descriptions-item label="订单编号" :span="2">{{ form.orderCode }}</el-descriptions-item>
        <el-descriptions-item label="订单日期">
          <el-tag size="small">{{ form.orderDate }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建日期">{{ form.orderCreatetime }}</el-descriptions-item>
        <el-descriptions-item label="销售部门"> {{ form.sailDepart }}</el-descriptions-item>
        <el-descriptions-item label="业务员"> {{ form.productCode }}</el-descriptions-item>
        <el-descriptions-item label="跟单员">{{ form.productName }}</el-descriptions-item>
        <el-descriptions-item label="订单数量">{{ form.orderNum }}</el-descriptions-item>
        <el-descriptions-item label="总体进度">{{ form.progress }}</el-descriptions-item>
        <el-descriptions-item label="订单备注" :span="2">{{ form.orderRemark }}</el-descriptions-item>
      </el-descriptions>
      <el-divider></el-divider>
      <el-table v-loading="loading"
                show-summary
                border :data="orderproductList" @selection-change="handleSelectionChange">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="产品编码" align="center" prop="productCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="规格型号" align="center" prop="productStandard" />
        <el-table-column label="产品单位" align="center" prop="productUnit" />
        <el-table-column label="产品数量" align="center" prop="productNum" />
        <el-table-column label="备注" align="center" prop="productRemark" />
        <el-table-column label="已分单数量" align="center" prop="workerOrdernum" />
        <!--<el-table-column label="分单状态" align="center" prop="workerOrderstatus" />-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleBomView(scope.row)"
              v-hasPermi="['order:orderinfo:edit']">查看BOM</el-button>
            <!--<el-button size="mini" type="text" icon="el-icon-edit" @click="handlePrint(scope.row)"
              v-hasPermi="['order:orderinfo:edit']">打印产品</el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total3 > 0" :total="total3" :page.sync="queryParams2.pageNum"
        :limit.sync="queryParams2.pageSize" @pagination="getProductList" />
    </el-dialog>

    <el-dialog title="BOM详情数据" :visible.sync="bomopen" width="1200px" append-to-body>
      <el-table
        :data="bominfoList"
        style="width: 100%"
        row-key="id"
        border
        lazy
        :load="load"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column label="子项物料编码" align="center" prop="bomCode" />
          <el-table-column label="物料名称" align="center" prop="bomName">
          </el-table-column>
          <el-table-column label="规格型号" align="center" prop="bomStandard" />
          <el-table-column label="物料属性" align="center" prop="bomAttribute">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.bom_attribute" :value="scope.row.bomAttribute" />
            </template>
          </el-table-column>
          <el-table-column label="BOM版本" align="center" prop="bomVersion" />
          <el-table-column label="单位" align="center" prop="bomUnit" />
      </el-table>

      <!--<el-table v-loading="loading" :data="bominfoList">
        <el-table-column label="子项物料编码" align="center" prop="bomCode" />
        <el-table-column label="物料名称" align="center" prop="bomName" />
        <el-table-column label="规格型号" align="center" prop="bomStandard" />
        <el-table-column label="物料属性" align="center" prop="bomAttribute">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.bom_attribute" :value="scope.row.bomAttribute" />
          </template>
        </el-table-column>
        <el-table-column label="BOM版本" align="center" prop="bomVersion" />
        <el-table-column label="单位" align="center" prop="bomUnit" />-->
        <!--<el-table-column label="分子" align="center" prop="numerator" />
        <el-table-column label="分母" align="center" prop="denominator" />-->
     <!-- </el-table>-->
    </el-dialog>

    <el-dialog title="产品详情数据"
               border :visible.sync="progressopen" height="800" style="width: 100%;overflow: auto">
      <el-table border v-loading="loading" :data="progressProductList"
                show-summary>
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="产品编码" align="center" prop="productCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="规格型号" align="center" prop="productStandard" />
        <el-table-column label="产品单位" align="center" prop="productUnit" />
        <el-table-column label="产品数量" align="center" prop="productNum" />
        <el-table-column label="完工数量" align="center" prop="finishedCount" />
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="progressParams.pageNum"
        :limit.sync="progressParams.pageSize"
        @pagination="showProgressList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listOrderinfo, syncOrder,syncOneOrder, getOrderinfo, createSailOrderinfo, delOrderinfo, addOrderinfo, updateOrderinfo, headOrderCancel }
from "@/api/sm/order/orderinfo";
import { listOrderproduct,printProduct } from "@/api/sm/order/orderproduct";
import { listAllBominfo,listChildren } from "@/api/sm/basic/bominfo";
export default {
  name: "Orderinfo",
  dicts: ['order_status','bom_attribute'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      createtotal: 0,
      total3: 0,
      // 订单信息表格数据
      orderinfoList: [],
      orderCreateinfoList: [],
      orderproductList: [],
      bominfoList: [],
      progressProductList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      viewopen: false,
      progressopen: false,
      bomopen: false,
      // 同步时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParamsOfDialog: {
        pageNum: 1,
        pageSize: 20,
        contractCode: null,
        customName: null,
        orderCode: null,
        orderDate: null,
        orderStatus: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        contractCode: null,
        customName: null,
        orderDate: null,
        orderStatus: null,
        orderStatuss: "1,10,11,20,21,30,40,50"
      },
      // 查询参数
      queryParams2: {
        pageNum: 1,
        pageSize: 20,
        orderCode: null
      },
      progressParams: {
        pageNum: 1,
        pageSize: 20,
        orderCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleOneSync(row){
      this.loading = true;
      const id = row.id
      syncOneOrder(id).then(response => {
        this.loading = false;
        alert("同步完成");
      });
    },
    showProgressList() {
      this.showProgress(this.progressParams);
    },
    showProgress(row){
      Object.assign(this.progressParams, {orderCode: row.orderCode});
      this.loading = true;
      this.progressopen = true;
      listOrderproduct(this.progressParams).then(response => {
        this.progressProductList = response.rows || [];
        this.loading = false;
        this.total = response.total || 0;
      }).catch((error) => {
        this.loading = false;
      });
    },
    load(tree, treeNode, resolve) {
      listChildren({"parentBomCode":tree.bomCode,"productId":treeNode.productId}).then((res) => {   //getChildMenu是我们自己的调用后台的封装
          resolve(                            //resolve是组件的
              res.data  //根据自己的格式,将查到的子菜单数组填充
          )
      })
    },
    handlePrint(row) {
      this.loading = true;
      const ids = row.id || this.ids;
      printProduct(ids).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '订单产品信息'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },
    /** 查询订单产品信息列表 */
    getProductList() {
      this.loading = true;
      listOrderproduct(this.queryParams2).then(response => {
        this.orderproductList = response.rows || [];
        this.total3 = response.total || 0;
        this.loading = false;
      });
    },
    /** 查询订单信息列表 */
    getNeedToCreateList() {
      this.loading = true;
      const params = {};
      Object.assign(params, this.queryParamsOfDialog);
      params.orderStatuss = '0,1';
      listOrderinfo(params).then(response => {
        this.orderCreateinfoList = response.rows;
        this.createtotal = response.total;
        this.loading = false;
      });
    },
    /** 查询订单信息列表 */
    getCreateList() {
      this.loading = true;
      listOrderinfo(this.queryParamsOfDialog).then(response => {
        this.orderCreateinfoList = response.rows;
        this.createtotal = response.total;
        this.loading = false;
      });
    },

    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeOrderDate && '' != this.daterangeOrderDate) {
        this.queryParams.params["beginOrderDate"] = this.daterangeOrderDate[0];
        this.queryParams.params["endOrderDate"] = this.daterangeOrderDate[1];
      }
      listOrderinfo(this.queryParams).then(response => {
        this.orderinfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        contractCode: null,
        customName: null,
        orderCode: null,
        orderDate: null,
        orderCreatetime: null,
        sailDepart: null,
        documentaryName: null,
        businessName: null,
        orderNum: null,
        status: null,
        planStatus: null,
        progress: null,
        orderRemark: null,
        syncTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQueryOfDialog() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单信息";
    },
    /** 订单详情按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id
      getOrderinfo(id).then(response => {
        this.viewopen = true;
        this.form = response.data;
        this.title = "订单详情";
      });
      this.queryParams2.orderCode = row.orderCode;
      this.getProductList();
    },
    headOrderCancel(row) {
      this.loading = true;
      const that = this;
      this.$modal.confirm(`确认要删除 ${row.orderCode} 总部订单吗？`).then(function() {
        headOrderCancel({"orderCode": row.orderCode})
          .then(response => {
            that.loading = false;
            that.$modal.msgSuccess("删除成功");
            that.getList();
          }).catch(() => {});
      }).then(() => {
      }).catch(() => {
        this.loading = false;
      });
    },
    handleBomView(row) {
      listChildren({"productId":row.productId,"parentBomCode":row.productCode}).then(response => {
        this.bomopen = true;
        this.bominfoList = response.data;
        this.title = "BOM详情";
      });

    },
    handleSync() {
      this.loading = true;
      syncOrder().then(response => {
        this.open = true;
        this.getNeedToCreateList();
        this.title = "创建销售订单";
        this.loading = false;
      });
    },
    handleCreateOrder(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('确认创建销售订单').then(function () {
        return createSailOrderinfo(ids);
      }).then(() => {
        this.getNeedToCreateList();
        this.getList();
        this.$modal.msgSuccess("创建成功");
      }).catch(() => { });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrderinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrderinfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单信息编号为"' + ids + '"的数据项？').then(function () {
        return delOrderinfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('orderinfo/orderinfo/export', {
        ...this.queryParams
      }, `orderinfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss">
.blockRed {
  td {
    color: rgb(234, 77, 77) !important;
  }
}
</style>
